<?php

class Code_model extends CI_Model {


    function __construct()
    {
        parent::__construct();
    }

    public function allot_code($uid, $type)
    {
        $query = $this->db->get_where('code', array('type' => $type, 'is_used' => FALSE), 1);
        $result = $query->row();
        if ($result) {
            $this->_allot_code($uid, $result->code);
            return $result->code;
        } else {
            return FALSE;
        }

    }

    public function check_user($uid)
    {
        $this->db->join('code', 'code.code = user.code', 'left');
        $query = $this->db->get_where('user', array('uid'=>$uid), 1);
        $result = $query->row();
        if ($result->code) {
            return $result;
        } else {
            return FALSE;
        }
    }

    public function _allot_code($uid, $code)
    {
        $this->db->trans_start();
        $this->db->query('UPDATE NBA_code set is_used = 1 where code = ?;', array($code));
        $this->db->query('UPDATE NBA_user set code = ? where uid = ?;', array($code, $uid));
        $this->db->trans_complete();
    }

    public function get_by_uid($type)
    {
        $query = $this->db->get_where('code', array('type' => $type), 1);
        return $query->row();
    }
}
